package com.kcs.dc.report.model.logic;

import java.sql.Connection;
import java.util.Date;
import com.authen.ldap.KCS_LDAPEntry;
import com.authen.ldap.LDAPUtil;
import com.kcs.common.framework.GenericDto;
import com.kcs.common.utils.Based64Utils;
import com.kcs.common.utils.ConnectionUtils;
import com.kcs.common.utils.Constant;
import com.kcs.common.utils.ConstantMessage;
import com.kcs.common.utils.LogWriter;
import com.kcs.common.utils.PropsUtils;
import com.kcs.common.utils.commonUtils;
import com.kcs.dc.report.model.dao.CommonDAO;
import com.kcs.dc.report.model.dao.loginDAO;
import com.kcs.dc.report.model.dao.model.userActiveModel;
import com.kcs.dc.report.view.dto.LoginDto;
import com.kcs.dc.report.view.dto.MainMenuDto;

public class loginBL {
	private String user_id = null;
	private String password = null;
	private loginDAO dao = null;
	private CommonDAO daoCommon = null;
	private Connection conn = null;
	private String NON_ACTIVE = "N";
	
	public loginBL() {
		dao = new loginDAO();
		daoCommon = new CommonDAO();
	}
	
	public GenericDto loginEvent(LoginDto dto) throws Exception{
		
		LogWriter.debug("<=====Start login Event=====>", Constant.LOGGER_APPLICATION);
		
		user_id = dto.getUserId();
		password = dto.getPassword();
		
		basicCheck(dto);
		if(dto.getMessageCode().equals("")){
			
			// 'ADMIN' don't check LDAP but check Password : p@s$w0rD;K1b
			if(user_id.equals(PropsUtils.getMessage(Constant.PROP_OTHER, "user.admin"))){
				if(!Based64Utils.base64encode(password).equals(PropsUtils.getMessage(Constant.PROP_OTHER, "user.pass"))){
					dto.setFocus_Attr("userId");
					dto.setUser_Attr(Constant.ERR_ATTR);
		        	dto.setMessage(Constant.PROP_REPORT, ConstantMessage.ERR_AUTHEN_USER, new String[]{user_id});
		 
		        	dto.setService_id("login");     
				}else{
					//Set value to GenericForm       	
		        	dto.setUserId(user_id);
		        	dto.setPasswordEncode(Based64Utils.base64encode(dto.getPassword()));
		        	dto.setUserName(PropsUtils.getMessage(Constant.PROP_OTHER, "user.admin"));
				}
			}else{
				// send LDAP
				checkLDAP(dto);
			}
			
			
			if(dto.getMessageCode().equals("")){
				if(!user_id.equals(PropsUtils.getMessage(Constant.PROP_OTHER, "user.admin"))){
					// check status isActive.
					checkActive(dto);
				}
				
				if (dto.getMessageCode().equals("")) {
					LogWriter.info("Login by userID: "+ dto.getUserId() + ", UserName: " + dto.getUserName(), Constant.LOGGER_APPLICATION);
					LogWriter.info("@Last_access_Time: "+ dto.getLastaccessTime() + ".", Constant.LOGGER_APPLICATION);
					LogWriter.info("@Operation_Time :" + commonUtils.formatDate(new Date(Long.parseLong(dto.getOperationTime())), commonUtils.ddmmyyyyhhmmsswithslash), Constant.LOGGER_APPLICATION);
									
					MainMenuDto menuDto = new MainMenuDto();
					menuDto.populate(dto);
					menuDto.setService_id("welcome");

					return menuDto;				
				} 
			}
		}
		
		return dto;
	}
	
	private void basicCheck(LoginDto dto) {
		/* Basic check function */
		LogWriter.debug("Step 1 : basicCheck (must to input all)", Constant.LOGGER_APPLICATION);
		
		if (user_id.equals("")){
			dto.setFocus_Attr("userId");
			dto.setUser_Attr(Constant.ERR_ATTR); 
			dto.setMessage(Constant.PROP_REPORT, ConstantMessage.ERR_USER_BLANK, null);
		
			dto.setService_id("login");
		
		}else if (password.equals("")){
			dto.setFocus_Attr("password");
			dto.setPassword_Attr(Constant.ERR_ATTR); 
			dto.setMessage(Constant.PROP_REPORT, ConstantMessage.ERR_PASS_BLANK, null);
		
			dto.setService_id("login");		
		}
	}
	
	private void checkLDAP(LoginDto dto){
        
		LogWriter.debug("Step 2 : checkLDAP", Constant.LOGGER_APPLICATION);
		
		LDAPUtil test = new LDAPUtil();    		  
        KCS_LDAPEntry ent = test.authenticateUser(user_id, password, user_id);
        
        if (ent != null) {
            //Set value to GenericForm       	
        	dto.setUserId(user_id);
        	dto.setPasswordEncode(Based64Utils.base64encode(dto.getPassword()));
        	dto.setUserName(ent.getThaiFirstName() + " " + ent.getThaiLastName());
                       
        } else {
             
        	dto.setFocus_Attr("userId");
			dto.setUser_Attr(Constant.ERR_ATTR);
        	dto.setMessage(Constant.PROP_REPORT, ConstantMessage.ERR_AUTHEN_USER, new String[]{user_id});
 
        	dto.setService_id("login");       	       	
        }
     
	}
	
	private void checkActive(LoginDto dto){

		LogWriter.debug("Step 3 : checkActive & update login", Constant.LOGGER_APPLICATION);
		
		conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO);
		userActiveModel[] model = null;
        
		try{
			model = daoCommon.getUserActive(user_id, "", "", conn);	        
			
	        if (model == null || model[0].getActive_stauts().equals(NON_ACTIVE)) {
	        	
	        	dto.setFocus_Attr("userId");
	        	dto.setUser_Attr(Constant.ERR_ATTR);
	        	dto.setMessage(Constant.PROP_REPORT, ConstantMessage.ERR_CANNOT_USE_SYS, null);
	        		        	 
	        	dto.setService_id("login");
	            
	        } else {
	                	
	        	dto.setLastaccessTime(model[0].getLast_access_time());
	        	
	        	//Update user login on deal center.
	        	dao.updateUserLogin(user_id, dto.getUserName(), conn);	        	
	        	
	        }
  
		}catch(Exception e){
			LogWriter.error("loginBL [Method : checkActive] : " + e.getMessage(), Constant.LOGGER_APPLICATION);
		}finally{
			ConnectionUtils.closeConnection(conn);
		}
	}	
	
	public GenericDto initEvent(LoginDto dto) throws Exception {
		try {
			dto.setUser_Attr("");
			dto.setPassword_Attr("");
			dto.setUserId("");
			dto.setPassword("");
			
			dto.setService_id("login");
		} catch (Exception e) {
			LogWriter.error("loginBL [Method : previousEvent] :" + e.getMessage(), Constant.LOGGER_APPLICATION);
		}
		return dto;
	}

}
